const jwt = require('jsonwebtoken')
const assert = require('http-assert')
const AdminUser = require('../db/model/adminUser')

const auth = async (req, res, next) => {
  assert(req.headers.authorization, 401, '请先登录')
  const token = req.headers.authorization.split('Bearer ')[1]
  assert(token, 401, '请先登录')
  const userId = jwt.verify(token, process.env.SECRET)
  const user = await AdminUser.findById(userId.id)
  assert(user, 401, '无此用户')
  next()
}

module.exports = {
  auth
}
